<template>
  <div class="role-permission-management">
    <div class="header">
      <h2>角色权限管理</h2>
      <p>管理员可以在此为角色分配或取消权限</p>
    </div>

    <!-- 角色列表和权限分配 -->
    <div class="content">
      <el-row :gutter="20">
        <!-- 左侧角色列表 -->
        <el-col :span="8">
          <el-card class="role-list-card">
            <template #header>
              <div class="card-header">
                <span>角色列表</span>
                <el-button type="primary" size="small" @click="showCreateRoleDialog">
                  <el-icon><Plus /></el-icon>
                  新增角色
                </el-button>
              </div>
            </template>
            <div class="role-list">
              <el-table
                :data="roles"
                highlight-current-row
                @current-change="handleRoleSelect"
                style="width: 100%"
              >
                <el-table-column prop="name" label="角色名称" />
                <el-table-column prop="description" label="角色描述" />
                <el-table-column label="操作" width="120">
                  <template #default="scope">
                    <el-button
                      v-if="!isSystemRole(scope.row.name)"
                      size="small"
                      type="danger"
                      @click="deleteRole(scope.row)"
                    >
                      删除
                    </el-button>
                    <el-tooltip
                      v-else
                      content="系统角色不可删除"
                      placement="top"
                    >
                      <el-icon style="font-size: 16px; color: #909399; cursor: not-allowed;">
                        <Lock />
                      </el-icon>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-col>

        <!-- 右侧权限分配 -->
        <el-col :span="16">
          <el-card class="permission-card">
            <template #header>
              <div class="card-header">
                <span v-if="selectedRole">权限分配 - {{ selectedRole.name }}</span>
                <span v-else>请选择角色</span>
              </div>
            </template>
            <div v-if="selectedRole" class="permission-content">
              <!-- 权限搜索 -->
              <div class="permission-search">
                <el-input
                  v-model="permissionSearch"
                  placeholder="搜索权限..."
                  clearable
                  style="width: 300px; margin-bottom: 20px"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
              </div>

              <!-- 权限列表 -->
              <div class="permission-list">
                <el-table
                  :data="filteredPermissions"
                  row-key="id"
                  style="width: 100%"
                >
                  <el-table-column prop="name" label="权限名称" width="200" />
                  <el-table-column prop="description" label="权限描述" />
                  <el-table-column label="状态" width="100">
                    <template #default="scope">
                      <el-tag :type="hasPermission(selectedRole.name, scope.row.name) ? 'success' : 'info'">
                        {{ hasPermission(selectedRole.name, scope.row.name) ? '已分配' : '未分配' }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="120">
                    <template #default="scope">
                      <el-button
                        v-if="!hasPermission(selectedRole.name, scope.row.name)"
                        size="small"
                        type="primary"
                        @click="assignPermission(scope.row)"
                      >
                        分配
                      </el-button>
                      <el-button
                        v-else
                        size="small"
                        type="warning"
                        @click="removePermission(scope.row)"
                      >
                        取消
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <!-- 分页组件 -->
                <div class="pagination-container" style="margin-top: 20px; text-align: center;">
                  <el-pagination
                    v-model:current-page="permissionPagination.currentPage"
                    v-model:page-size="permissionPagination.pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="permissionPagination.total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                  />
                </div>
              </div>
            </div>
            <div v-else class="no-role-selected">
              <el-empty description="请选择一个角色进行权限管理" />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 新增角色对话框 -->
    <el-dialog
      v-model="createRoleDialogVisible"
      title="新增角色"
      width="500px"
      @close="handleCreateRoleDialogClose"
    >
      <el-form
        :model="newRoleForm"
        :rules="newRoleFormRules"
        ref="newRoleFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="newRoleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="newRoleForm.description"
            type="textarea"
            placeholder="请输入角色描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createRoleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createRole">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Lock } from '@element-plus/icons-vue'
import { ROLE_PERMISSIONS } from '../../utils/auth.js'
import request from '@/utils/request'
import { useRouter } from 'vue-router'

// 角色数据
const roles = ref([])

// 权限数据
const permissions = ref([])

// 分页数据
const permissionPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 路由实例
const router = useRouter()

// 当前选中的角色
const selectedRole = ref(null)

// 权限搜索
const permissionSearch = ref('')

// 新增角色对话框
const createRoleDialogVisible = ref(false)

// 新角色表单
const newRoleForm = reactive({
  name: '',
  description: ''
})

// 表单引用
const newRoleFormRef = ref()

// 表单验证规则
const newRoleFormRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ]
}

// 过滤后的权限列表（带分页）
const filteredPermissions = computed(() => {
  let filteredData = permissions.value
  if (permissionSearch.value) {
    filteredData = permissions.value.filter(permission =>
      permission.name.includes(permissionSearch.value) ||
      permission.description.includes(permissionSearch.value)
    )
  }

  // 更新总数量
  permissionPagination.total = filteredData.length

  // 计算分页数据
  const start = (permissionPagination.currentPage - 1) * permissionPagination.pageSize
  const end = start + permissionPagination.pageSize
  return filteredData.slice(start, end)
})

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  permissionPagination.pageSize = val
  permissionPagination.currentPage = 1
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  permissionPagination.currentPage = val
}

// 处理角色选择
const handleRoleSelect = async (role: any) => {
  try {
    // 获取角色的实际权限
    const response = await request.get(`/api/roles/${role.id}/permissions`)
    role.permissions = response.data.map((p: any) => ({
      id: p.id,
      name: p.permissionCode,
      description: p.description
    }))
    selectedRole.value = role
  } catch (error) {
    ElMessage.error('获取角色权限失败')
    selectedRole.value = role
  }
}

// 检查角色是否具有某个权限
const hasPermission = (roleName: string, permissionName: string) => {
  // 首先检查内存中的权限
  if (ROLE_PERMISSIONS[roleName] && ROLE_PERMISSIONS[roleName].includes(permissionName)) {
    return true
  }

  // 如果内存中没有，检查当前选中角色的实际权限
  if (selectedRole.value && selectedRole.value.name === roleName && selectedRole.value.permissions) {
    return selectedRole.value.permissions.some((p: any) => p.name === permissionName)
  }

  return false
}

// 检查是否为系统角色
const isSystemRole = (roleName: string) => {
  const systemRoles = ['ADMIN', 'LECTURER', 'STUDENT', 'AUDITOR']
  return systemRoles.includes(roleName)
}

// 分配权限
const assignPermission = async (permission: any) => {
  if (!selectedRole.value) return

  // 检查权限是否已经分配
  if (selectedRole.value.permissions && selectedRole.value.permissions.some((p: any) => p.id === permission.id)) {
    ElMessage.info(`权限 ${permission.name} 已经分配给角色 ${selectedRole.value.name}`)
    return
  }

  try {
    // 获取角色当前的所有权限
    const response = await request.get(`/api/roles/${selectedRole.value.id}/permissions`)
    let currentPermissions = response.data.map(p => p.id)

    // 添加新权限
    if (!currentPermissions.includes(permission.id)) {
      currentPermissions.push(permission.id)
    }

    // 去除重复的权限ID
    currentPermissions = [...new Set(currentPermissions)]

    // 调用后端API来分配权限
    await request.post(`/api/roles/${selectedRole.value.id}/permissions`, currentPermissions)
    ElMessage.success(`已为角色 ${selectedRole.value.name} 分配权限 ${permission.name}`)

    // 更新本地数据
    if (!ROLE_PERMISSIONS[selectedRole.value.name]) {
      ROLE_PERMISSIONS[selectedRole.value.name] = []
    }
    if (!ROLE_PERMISSIONS[selectedRole.value.name].includes(permission.name)) {
      ROLE_PERMISSIONS[selectedRole.value.name].push(permission.name)
    }

    // 更新当前角色的权限列表
    if (!selectedRole.value.permissions) {
      selectedRole.value.permissions = []
    }
    selectedRole.value.permissions.push(permission)
    // 强制触发响应式更新
    selectedRole.value = { ...selectedRole.value }
  } catch (error: any) {
    console.error('分配权限失败:', error)
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(`分配权限失败: ${error.response.data.message}`)
    } else {
      ElMessage.error('分配权限失败')
    }
  }
}

// 取消权限
const removePermission = async (permission: any) => {
  if (!selectedRole.value) return

  // 检查权限是否已经分配
  if (!selectedRole.value.permissions || !selectedRole.value.permissions.some((p: any) => p.id === permission.id)) {
    ElMessage.info(`权限 ${permission.name} 尚未分配给角色 ${selectedRole.value.name}`)
    return
  }

  try {
    // 获取角色当前的所有权限
    const response = await request.get(`/api/roles/${selectedRole.value.id}/permissions`)
    let currentPermissions = response.data.map(p => p.id)

    // 移除权限
    currentPermissions = currentPermissions.filter(id => id !== permission.id)

    // 去除重复的权限ID
    currentPermissions = [...new Set(currentPermissions)]

    // 调用后端API来更新权限
    await request.post(`/api/roles/${selectedRole.value.id}/permissions`, currentPermissions)
    ElMessage.success(`已为角色 ${selectedRole.value.name} 取消权限 ${permission.name}`)

    // 更新本地数据
    if (ROLE_PERMISSIONS[selectedRole.value.name]) {
      const index = ROLE_PERMISSIONS[selectedRole.value.name].indexOf(permission.name)
      if (index > -1) {
        ROLE_PERMISSIONS[selectedRole.value.name].splice(index, 1)
      }
    }

    // 更新当前角色的权限列表
    if (selectedRole.value.permissions) {
      const index = selectedRole.value.permissions.findIndex((p: any) => p.id === permission.id)
      if (index > -1) {
        selectedRole.value.permissions.splice(index, 1)
        // 强制触发响应式更新
        selectedRole.value = { ...selectedRole.value }
      }
    }
  } catch (error: any) {
    console.error('取消权限失败:', error)
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(`取消权限失败: ${error.response.data.message}`)
    } else {
      ElMessage.error('取消权限失败')
    }
  }
}

// 显示创建角色对话框
const showCreateRoleDialog = () => {
  createRoleDialogVisible.value = true
}

// 处理创建角色对话框关闭
const handleCreateRoleDialogClose = () => {
  newRoleForm.name = ''
  newRoleForm.description = ''
  if (newRoleFormRef.value) {
    newRoleFormRef.value.resetFields()
  }
}

// 创建角色
const createRole = async () => {
  if (!newRoleFormRef.value) return

  await newRoleFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 调用后端API来创建角色
        const response = await request.post('/api/roles', {
          roleName: newRoleForm.name,
          roleDescription: newRoleForm.description
        })

        // 更新本地数据
        const createdRole = {
          id: response.data.id,
          name: response.data.roleName,
          description: response.data.roleDescription
        }
        roles.value.push(createdRole)

        createRoleDialogVisible.value = false
        ElMessage.success('角色创建成功')

        // 重置表单
        newRoleForm.name = ''
        newRoleForm.description = ''
      } catch (error) {
        ElMessage.error('角色创建失败')
      }
    }
  })
}

// 删除角色
const deleteRole = (role: any) => {
  if (isSystemRole(role.name)) {
    ElMessage.error('不能删除系统默认角色')
    return
  }

  ElMessageBox.confirm(
    `确定要删除角色 "${role.name}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 调用后端API来删除角色
      await request.delete(`/api/roles/${role.id}`)

      const index = roles.value.findIndex(r => r.name === role.name)
      if (index > -1) {
        roles.value.splice(index, 1)

        // 如果删除的是当前选中的角色，清空选中
        if (selectedRole.value && selectedRole.value.name === role.name) {
          selectedRole.value = null
        }

        ElMessage.success('角色删除成功')
      }
    } catch (error: any) {
      console.error('角色删除失败:', error)
      if (error.response && error.response.data && error.response.data.message) {
        ElMessage.error(error.response.data.message)
      } else {
        ElMessage.error('角色删除失败')
      }
    }
  }).catch(() => {
    // 取消删除
  })
}

// 组件挂载时的初始化逻辑
onMounted(() => {
  // 从后端获取最新的角色和权限数据
  fetchRoles()
  fetchPermissions()
})

// 获取角色列表
const fetchRoles = async () => {
  try {
    const response = await request.get('/api/roles')
    roles.value = response.data.map(role => ({
      id: role.id,
      name: role.roleName,
      description: role.roleDescription,
      permissions: [] // 初始化权限数组
    }))
  } catch (error) {
    ElMessage.error('获取角色列表失败')
  }
}

// 获取权限列表
const fetchPermissions = async () => {
  try {
    const response = await request.get('/api/roles/permissions')
    permissions.value = response.data.map(permission => ({
      id: permission.id,
      name: permission.permissionCode,
      description: permission.description
    }))
  } catch (error) {
    ElMessage.error('获取权限列表失败')
  }
}
</script>

<style scoped>
.role-permission-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  color: #303133;
  margin-bottom: 10px;
}

.header p {
  color: #606266;
  margin: 0;
}

.content {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.role-list-card, .permission-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.role-list {
  height: 500px;
  overflow-y: auto;
}

.permission-content {
  height: 500px;
  display: flex;
  flex-direction: column;
}

.permission-search {
  margin-bottom: 20px;
}

.permission-list {
  flex: 1;
  overflow-y: auto;
}

.no-role-selected {
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
